package com.rf.richfitwheel.admin.iam.service.impl;

import com.rf.richfitwheel.admin.conf.IamPropertiesConfig;
import com.rf.richfitwheel.admin.contants.UrlConstant;
import com.rf.richfitwheel.admin.iam.HttpEntityJsonUtil;
import com.rf.richfitwheel.admin.iam.dao.PortalUsbKeyMapper;
import com.rf.richfitwheel.admin.iam.model.*;
import com.rf.richfitwheel.admin.iam.service.PortalUsbKeyService;
import com.rf.richfitwheel.admin.sys.dao.SysCertInfoMapper;
import com.rf.richfitwheel.admin.sys.model.Config;
import com.rf.richfitwheel.admin.sys.model.SysCertInfo;
import com.rf.richfitwheel.admin.sys.service.ConfigService;
import com.rf.richfitwheel.common.contants.Constant;
import com.rf.richfitwheel.common.utils.DateUtils;
import com.rf.richfitwheel.common.utils.UuidUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hushouquan
 */
@Service
public class PortalUsbKeyServiceImpl implements PortalUsbKeyService{
    private Logger log = LoggerFactory.getLogger(PortalUsbKeyServiceImpl.class);
    @Autowired
    private IamPropertiesConfig iamPropertiesConfig;
    @Autowired
    private RestTemplate restTemplateOuter;
    @Autowired
    private ConfigService configService;
    @Autowired
    private PortalUsbKeyMapper portalUsbKeyMapper;
    @Autowired
    private SysCertInfoMapper sysCertInfoMapper;
    /**
     * 从门户同步usb key数据并入库
     *
     * @param appId    在商网注册的集成编号
     * @param myDate   时间戳毫秒值
     * @param config   游标
     * @param countSyn 记录数
     * @return 记录数
     */
    @Override
    public Integer usbKeySynDo(String appId, long myDate, Config config, Integer countSyn) throws URISyntaxException, IOException{
        //数据同步的游标
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("hostname", iamPropertiesConfig.getHostnameByAppId(appId));
        CloseableHttpResponse response = HttpEntityJsonUtil.executeApi(iamPropertiesConfig.getAccessKeyByAppId(appId),
                iamPropertiesConfig.getSecretKeyByAppId(appId), appId, "GET", null, headerMap,
                iamPropertiesConfig.getUrl() + UrlConstant.IAM_API_USB_KEY_SYNC, config.getParamValue());
        int statusCode = response.getStatusLine().getStatusCode();
        HttpEntity entity = response.getEntity();
        if(statusCode == org.apache.http.HttpStatus.SC_OK){
//            log.info("接收到的usbkey数据{}", EntityUtils.toString(entity));
            IamReturnUsbKeySyn iamReturnUsbKeySyn = HttpEntityJsonUtil.httpEntityContentToJsonArray(entity, IamReturnUsbKeySyn.class);
            if(iamReturnUsbKeySyn != null && iamReturnUsbKeySyn.getCode() == 200){
                PortalUsbKeySyn portalUsbKeySyn = iamReturnUsbKeySyn.getData();
                List<PortalUsbKeyInf> records = portalUsbKeySyn.getRecords();
                //入库序号
                long number = countSyn;
                for(PortalUsbKeyInf portalUsbKeyInf : records){
                    log.info("同步记录{}", portalUsbKeyInf);
                    PortalUsbKey portalUsbKey = new PortalUsbKey();
                    portalUsbKey.setId(UuidUtil.get32UUID());
                    portalUsbKey.setMyTime(myDate);
                    portalUsbKey.setBindUserId(portalUsbKeyInf.getBIND_USER_ID());
                    portalUsbKey.setCertificateDn(portalUsbKeyInf.getCERTIFICATE_DN());
                    portalUsbKey.setEndDate(portalUsbKeyInf.getEND_DATE());
                    portalUsbKey.setStatus(portalUsbKeyInf.getSTATUS());
                    portalUsbKey.setStartDate(portalUsbKeyInf.getSTART_DATE());
                    portalUsbKey.setSyncTime(++number);
                    portalUsbKey.setUkeyNo(portalUsbKeyInf.getUKEY_NO());
                    portalUsbKey.setRefNo(portalUsbKeyInf.getREF());
                    portalUsbKeyMapper.insert(portalUsbKey);
                }
                countSyn = countSyn + records.size();
                log.info("已同步{}条usbKey数据", countSyn);
                config.setParamValue(portalUsbKeySyn.getNextCursor() + "");
                //如果还有记录的话递归继续执行
                if(portalUsbKeySyn.isHasMore()){
                    countSyn = usbKeySynDo(appId, myDate, config, countSyn);
                }
            }else{
                log.warn("调用门户同步usbKey数据失败：{}", iamReturnUsbKeySyn);
            }
            response.close();
        }else{
            String error = EntityUtils.toString(entity);
            log.error("调用门户同步usbKey数据失败：{}", error);
        }
        return countSyn;
    }
    
    /**
     * 在数据已同步入库的情况下将数据处理至正式表
     *
     * @param myDate 时间戳毫秒值
     */
    @Override
    public void usbKeyDeal(long myDate) throws Exception{
        PortalUsbKeyExample example = new PortalUsbKeyExample();
        PortalUsbKeyExample.Criteria criteria = example.createCriteria();
        criteria.andMyTimeEqualTo(myDate);
        example.setOrderByClause(" sync_time ");
        List<PortalUsbKey> portalUsbKeyList = portalUsbKeyMapper.selectByExample(example);
        int count = 0;
        for(PortalUsbKey portalUsbKey : portalUsbKeyList){
            SysCertInfo sysCertInfo = null;
            sysCertInfo = sysCertInfoMapper.selectByPrimaryKey(portalUsbKey.getUkeyNo());
            if(sysCertInfo == null){
                //新增
                sysCertInfo = new SysCertInfo();
                sysCertInfo.setCertSn(portalUsbKey.getUkeyNo());
                sysCertInfo.setSubjectDn(portalUsbKey.getCertificateDn());
                sysCertInfo.setTemplateName(null);
                sysCertInfo.setRegistTime(null);
                sysCertInfo.setApplyTime(null);
                sysCertInfo.setStartTime(DateUtils.stringToDate(portalUsbKey.getStartDate(), DateUtils.DATE_TIME_PATTERN));
                sysCertInfo.setEndTime(DateUtils.stringToDate(portalUsbKey.getEndDate(), DateUtils.DATE_TIME_PATTERN));
                sysCertInfo.setCertStatus(portalUsbKey.getStatus());
                sysCertInfo.setExpired(Constant.COMMON_YES_OR_NO_NO);
                sysCertInfo.setReceStatus(null);
                sysCertInfo.setRefNo(portalUsbKey.getRefNo());
                sysCertInfo.setAuthCode(null);
                sysCertInfo.setPublicKey(null);
                sysCertInfo.setRevokeReason(null);
                sysCertInfo.setUserId(portalUsbKey.getBindUserId());
                sysCertInfo.setPayment(Constant.COMMON_YES_OR_NO_NO);
                sysCertInfo.setPaymentStatus("1");
                try{
                    sysCertInfoMapper.insertSelective(sysCertInfo);
                }catch(Exception e){
                    log.error(e.getMessage(), e);
                }
            }else{
                //修改
                sysCertInfo.setCertSn(portalUsbKey.getUkeyNo());
                sysCertInfo.setSubjectDn(portalUsbKey.getCertificateDn());
                sysCertInfo.setStartTime(DateUtils.stringToDate(portalUsbKey.getStartDate(), DateUtils.DATE_TIME_PATTERN));
                sysCertInfo.setEndTime(DateUtils.stringToDate(portalUsbKey.getEndDate(), DateUtils.DATE_TIME_PATTERN));
                sysCertInfo.setCertStatus(portalUsbKey.getStatus());
                sysCertInfo.setUserId(portalUsbKey.getBindUserId());
                try{
                    sysCertInfoMapper.updateByPrimaryKeySelective(sysCertInfo);
                }catch(Exception e){
                    log.error(e.getMessage(), e);
                }
            }
            count++;
            if(count % 500 == 0 || count == portalUsbKeyList.size()){
                log.info("已处理{}/{}条数据", count, portalUsbKeyList.size());
            }
        }
        log.info("共处理{}条数usbKey数据", portalUsbKeyList.size());
    }
}
